<template>
  <div class="addr-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="list-header">
          <h2>地址列表</h2>
          <div class="header-actions">
            <el-tooltip content="新增地址" placement="bottom">
              <el-button
                  type="primary"
                  @click="handleAddAddr"
                  size="small"
                  class="icon-btn"
              >
                <el-icon><Plus /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="关闭" placement="bottom">
              <el-button
                  type="info"
                  @click="$emit('closeLogAdrList')"
                  size="small"
                  class="icon-btn"
              >
                <el-icon><Close /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="名称">
          <el-input
              v-model="searchForm.name"
              placeholder="请输入名称"
              clearable
              style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="地址">
          <el-input
              v-model="searchForm.host"
              placeholder="请输入地址"
              clearable
              style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="库名">
          <el-input
              v-model="searchForm.dbName"
              placeholder="请输入库名"
              clearable
              style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="表名">
          <el-input
              v-model="searchForm.tableName"
              placeholder="请输入表名"
              clearable
              style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
              v-model="searchForm.deleted"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
          >
            <el-option label="正常" :value="0" />
            <el-option label="禁用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="tableLoading" :disabled="tableLoading" :icon="Search">搜索</el-button>
          <el-button @click="resetSearch" :disabled="tableLoading" :icon="RefreshRight">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 地址表格 -->
      <div class="table-container">
        <el-table
          :data="adrList"
          border
          style="width: 100%"
          v-loading="tableLoading"
          element-loading-text="加载中..."
          :empty-text="emptyText"
          stripe
          highlight-current-row
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column prop="name" label="名称" min-width="180" align="center" show-overflow-tooltip fixed="left" />
          <el-table-column prop="host" label="地址" min-width="220" align="center" show-overflow-tooltip />
          <el-table-column prop="port" label="端口号" min-width="100" align="center" />
          <el-table-column prop="userName" label="用户名" min-width="150" align="center" show-overflow-tooltip />
          <el-table-column prop="dbName" label="库名" min-width="180" align="center" show-overflow-tooltip />
          <el-table-column prop="tableName" label="表名" min-width="180" align="center" show-overflow-tooltip />
          <el-table-column prop="deleted" label="状态" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.deleted === 0 ? 'success' : 'warning'">
              {{ row.deleted === 0 ? '正常' : '已删除' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button size="small" type="primary" @click="handleEdit(row)" :icon="Edit">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)" :icon="Delete">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.pageNum"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :disabled="tableLoading"
            :hide-on-single-page="pagination.total <= pagination.pageSize"
            class="responsive-pagination"
        />
      </div>
    </el-card>

    <!-- 添加/编辑地址对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
    >
      <el-form ref="addrFormRef" :model="addrForm" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="addrForm.name" placeholder="请输入名称" maxlength="255" show-word-limit />
        </el-form-item>
        <el-form-item label="地址" prop="host">
          <el-input v-model="addrForm.host" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="端口号" prop="port">
          <el-input v-model="addrForm.port" placeholder="请输入端口号" />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addrForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input v-model="addrForm.passWord" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="testConnection" :loading="testLoading">测试连接</el-button>
        </el-form-item>
        <el-form-item label="库名" prop="dbName">
          <el-select
            v-model="addrForm.dbName"
            placeholder="请选择库名"
            :disabled="!connectionTested"
            @change="handleDbChange"
          >
            <el-option
                v-for="db in dbList"
                :key="db"
                :label="db"
                :value="db"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="表名" prop="tableName">
          <el-select
            v-model="addrForm.tableName"
            placeholder="请选择表名"
            :disabled="!addrForm.dbName"
          >
            <el-option
                v-for="table in tableList"
                :key="table"
                :label="table"
                :value="table"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="deleted">
          <el-radio-group v-model="addrForm.deleted">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Close, Edit, Delete, Search, RefreshRight } from '@element-plus/icons-vue'
import api from '@/api'
import { useTokenStore } from '@/stores/token'

// 搜索表单
const searchForm = reactive({
  name: '',
  host: '',
  dbName: '',
  tableName: '',
  deleted: ''
})

// 地址列表数据
const adrList = ref([])
const tableLoading = ref(false)
const emptyText = ref('暂无数据')

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 处理认证错误
const handleAuthError = () => {
  ElMessage.error('用户认证已过期，请重新登录')
  const tokenStore = useTokenStore()
  tokenStore.removeToken()
  window.location.href = '/login'
}

// 获取地址列表
const fetchadrList = async () => {
  tableLoading.value = true
  emptyText.value = '加载中...'
  try {
    // 准备查询参数
    const data = {
      name: searchForm.name,
      host: searchForm.host,
      dbName: searchForm.dbName,
      tableName: searchForm.tableName,
      deleted: searchForm.deleted
    }

    console.log('发起分页查询请求:', {
      data,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    })

    // 使用更新后的API方法，传递查询参数和分页参数
    const response = await api.binlog.list(data, pagination.pageNum, pagination.pageSize)

    // 检查响应中是否包含认证错误信息
    if (response.code === 401 || response.code === 403) {
      handleAuthError()
      return
    }

    if (response.code === 200 && response.data) {
      // 更新列表数据
      adrList.value = response.data.records || []
      
      // 更新分页信息
      pagination.total = response.data.total || 0
      // 不要覆盖当前页码，因为它是由分页组件控制的
      pagination.pageSize = response.data.size || 10

      // 设置空数据提示文本
      emptyText.value = searchForm.name || searchForm.host || searchForm.dbName || searchForm.tableName || searchForm.deleted !== ''
        ? '未找到匹配的数据'
        : '暂无数据'
    } else {
      ElMessage.error(response.msg || '获取地址失败')
      emptyText.value = '获取数据失败'
      adrList.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取地址失败:', error)
    // 检查错误是否为认证错误
    if (error.response && (error.response.status === 401 || error.response.status === 403)) {
      handleAuthError()
    } else {
      ElMessage.error('获取地址失败，请检查网络连接')
      adrList.value = []
      pagination.total = 0
      emptyText.value = '获取数据失败'
    }
  } finally {
    tableLoading.value = false
  }
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加地址')
const addrFormRef = ref(null)
const testLoading = ref(false)
const connectionTested = ref(false)
const dbList = ref([])
const tableList = ref([])

const addrForm = reactive({
  id: '',
  name: '',
  host: '',
  port: '',
  userName: '',
  passWord: '',
  dbName: '',
  tableName: '',
  deleted: 0
})

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { max: 255, message: '名称长度不能超过255个字符', trigger: 'blur' }
  ],
  host: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    { pattern: /^\d+$/, message: '端口号必须为数字', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  passWord: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  dbName: [
    { required: false, message: '请选择库名', trigger: 'change' }
  ],
  tableName: [
    { required: false, message: '请选择表名', trigger: 'change' }
  ]
})

// 测试数据库连接
const testConnection = async () => {
  try {
    const { host, port, userName, passWord } = addrForm
    if (!host || !port || !userName || !passWord) {
      ElMessage.warning('请填写完整的连接信息')
      return
    }

    testLoading.value = true
    const response = await api.binlog.test({ host, port, userName, passWord })

    if (response.code === 200) {
      ElMessage.success('连接测试成功')
      connectionTested.value = true
      // 获取数据库列表
      const dbResponse = await api.binlog.getDataBaseList({ host, port, userName, passWord })
      if (dbResponse.code === 200) {
        dbList.value = dbResponse.data || []
      }
    } else {
      ElMessage.error(response.msg || '连接测试失败')
      connectionTested.value = false
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    ElMessage.error('连接测试失败，请检查网络')
    connectionTested.value = false
  } finally {
    testLoading.value = false
  }
}

// 处理数据库选择变化
const handleDbChange = async () => {
  try {
    const { host, port, userName, passWord, dbName } = addrForm
    if (!dbName) {
      tableList.value = []
      return
    }

    const response = await api.binlog.getDataTableList({
      host,
      port,
      userName,
      passWord,
      dbName
    })

    if (response.code === 200) {
      tableList.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取表列表失败')
      tableList.value = []
    }
  } catch (error) {
    console.error('获取表列表失败:', error)
    ElMessage.error('获取表列表失败，请检查网络')
    tableList.value = []
  }
}

// 处理添加地址
const handleAddAddr = () => {
  dialogTitle.value = '添加地址'
  dialogVisible.value = true
  connectionTested.value = false
  dbList.value = []
  tableList.value = []
  nextTick(() => {
    if (addrFormRef.value) {
      addrFormRef.value.resetFields()
    }
    Object.assign(addrForm, {
      id: '',
      name: '',
      host: '',
      port: '',
      userName: '',
      passWord: '',
      dbName: '',
      tableName: '',
      deleted: 0
    })
  })
}

// 处理编辑地址
const handleEdit = (row) => {
  dialogTitle.value = '编辑地址'
  dialogVisible.value = true
  connectionTested.value = true
  nextTick(() => {
    Object.assign(addrForm, { ...row })
  })
}

// 处理删除地址
const handleDelete = (row) => {
  if (!row || !row.id) {
    ElMessage.error('无效的记录ID')
    return
  }

  ElMessageBox.confirm(
    `确定要删除该地址吗？\n地址：${row.host}:${row.port}\n数据库：${row.dbName}\n表：${row.tableName}`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false
    }
  ).then(async () => {
    try {
      const response = await api.binlog.delete({
        id: row.id
      })

      if (response.code === 200) {
        ElMessage.success('删除成功')
        // 如果当前页只有一条数据，且不是第一页，则跳转到上一页
        if (adrList.value.length === 1 && pagination.pageNum > 1) {
          pagination.pageNum--
        }
        fetchadrList()
      } else if (response.code === 401 || response.code === 403) {
        handleAuthError()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      if (error.response) {
        switch (error.response.status) {
          case 404:
            ElMessage.error('要删除的记录不存在')
            break
          case 500:
            ElMessage.error('服务器处理删除请求时出错')
            break
          default:
            ElMessage.error('删除失败，请检查网络连接')
        }
      } else {
        ElMessage.error('删除失败，请检查网络连接')
      }
    }
  }).catch(() => {
    // 用户取消删除操作，不需要任何处理
  })
}

// 提交表单
const submitForm = async () => {
  if (!addrFormRef.value) return
  
  await addrFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const method = addrForm.id ? 'updateByBinlogAddress' : 'add'
        const response = await api.binlog[method](addrForm)
        
        if (response.code === 200) {
          ElMessage.success(addrForm.id ? '更新成功' : '添加成功')
          dialogVisible.value = false
          fetchadrList()
        } else {
          ElMessage.error(response.msg || (addrForm.id ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error(addrForm.id ? '更新失败:' : '添加失败:', error)
        ElMessage.error(addrForm.id ? '更新失败，请检查网络' : '添加失败，请检查网络')
      }
    }
  })
}

// 处理搜索
const handleSearch = () => {
  pagination.pageNum = 1
  fetchadrList()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    name: '',
    host: '',
    dbName: '',
    tableName: '',
    deleted: ''
  })
  pagination.pageNum = 1
  fetchadrList()
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchadrList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.pageNum = val
  fetchadrList()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchadrList()
})
</script>

<style scoped>
.addr-list-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.icon-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.icon-btn:hover {
  transform: scale(1.1);
}

.icon-btn .el-icon {
  font-size: 16px;
}

@media screen and (max-width: 768px) {
  .icon-btn {
    width: 28px;
    height: 28px;
  }
  
  .icon-btn .el-icon {
    font-size: 14px;
  }
}

.search-form {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.responsive-pagination {
  --el-pagination-button-width: 32px;
  --el-pagination-button-height: 32px;
}

@media screen and (max-width: 768px) {
  .addr-list-container {
    padding: 10px;
  }

  .search-form {
    flex-direction: column;
  }

  .search-form .el-form-item {
    margin-right: 0;
  }

  .responsive-pagination {
    --el-pagination-button-width: 28px;
    --el-pagination-button-height: 28px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.table-container {
  margin-top: 20px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.el-table {
  min-width: 100%;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap;
}

@media screen and (max-width: 992px) {
  .operation-buttons {
    flex-direction: column;
    align-items: center;
  }
  
  .operation-buttons .el-button {
    margin-left: 0;
    margin-bottom: 5px;
    width: 100%;
  }
}
</style>